# -*- coding: utf-8 -*-
# @Time    : 2019/10/3 17:56
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer, AsyncJsonWebsocketConsumer


class MessagesConsumer(AsyncWebsocketConsumer):
    """处理私信应用中WebSocket请求"""

    async def connect(self):
        if self.scope["user"].is_anonymous:
            # 未登录的用户拒绝连接
            await self.close()
        else:
            # 加入聊天组,获取用户组要唯一，使用username；第二个参数是监听的频道名字
            await self.channel_layer.group_add(self.scope['user'].username, self.channel_name)
            await self.accept()

    async def receive(self, text_data=None, bytes_data=None):
        """接受私信"""
        await self.send(text_data=json.dumps(text_data))

    async def disconnect(self, code):
        """离开聊天组"""
        await self.channel_layer.group_discard(self.scope["user"].username, self.channel_name)


